package boc.sx.gateway.socket.client.handler;

import boc.sx.gateway.socket.client.NettyClient;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.util.Map;

import static com.sun.deploy.net.HttpRequest.CONTENT_TYPE;

/**
 * 客户端处理器
 */
public class HttpClientHandler extends ChannelHandlerAdapter {

    private String uri;

    private String code;

    private Object sendMsg;


    public HttpClientHandler(String uri, String code, Object sendMsg) {
        this.uri = uri;
        this.code = code;
        this.sendMsg = sendMsg;
    }

    public HttpClientHandler() {
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof  FullHttpResponse){
            FullHttpResponse response = (FullHttpResponse) msg;
            String s = response.content().toString(CharsetUtil.UTF_8);
            NettyClient.notifyThread(code,s);
        }
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        URI url = new URI(uri);
        //配置HttpRequest的请求数据和一些配置信息
        String msg = "";
        if(sendMsg instanceof  String){
            msg = (String)sendMsg;
        }else if(sendMsg instanceof JSONObject){
            msg = JSONObject.toJSONString(sendMsg);
        }else if(sendMsg instanceof Map){
            msg = JSONObject.toJSONString(sendMsg);
        }
        byte[] bytes = msg.getBytes();
        Unpooled.wrappedBuffer(bytes);
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, url.toASCIIString(),Unpooled.wrappedBuffer(bytes));
        request.headers().set(CONTENT_TYPE, "application/json");
        request.headers().set(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()+"");
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.close();
    }

}
